package com.usaas.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.usaas.common.constant.NormalConstant;
import com.usaas.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = getUserId();
        LocalDateTime now = LocalDateTime.now();
        Date nowDate = new Date();
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
        this.strictInsertFill(metaObject, "createTime", Date.class, nowDate);
        this.strictInsertFill(metaObject, "updateTime", Date.class, nowDate);
        this.strictInsertFill(metaObject, "createBy", String.class, userId);
        this.strictInsertFill(metaObject, "updateBy", String.class, userId);
        this.strictInsertFill(metaObject, "delFlag", Long.class, NormalConstant.NOTDEL);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = getUserId();
        LocalDateTime now = LocalDateTime.now();
        Date nowDate = new Date();
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, now);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, nowDate);
        this.strictUpdateFill(metaObject, "updateBy", String.class, userId);
    }

    private String getUserId() {
        Long userId = 1L;
        try {
            Long userIdT = SecurityUtils.getUserId();
            userId = userIdT == null ? 1L : userIdT;
        } catch (Exception e) {

        }
        return userId.toString();
    }


}
